package org.example.view;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;

public class HandleAddUser implements ActionListener {
    AddUserView addUserView;
    Socket socket=null;
    DataInputStream in=null;
    DataOutputStream out=null;
    Thread thread;
    public void setView(AddUserView addUserView) {
        this.addUserView = addUserView;
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        InetAddress address= null;
        socket=new Socket();
        thread=new Thread(addUserView);
        try {
            address = InetAddress.getByName("127.0.0.1");
            InetSocketAddress socketAddress=new InetSocketAddress
                    (address,4331);
            socket.connect(socketAddress);
            in =new DataInputStream(socket.getInputStream());
            out = new DataOutputStream(socket.getOutputStream());
            thread.start();
        } catch (IOException ex) {
            socket=new Socket();
        }

        if (e.getSource() == addUserView.submit){
            String s = null;
            s ="注册ID:"+addUserView.inputID.getText().trim()+ "姓名：" + addUserView.inputName.getText().trim();      //检查登陆状况
            if (addUserView.tea.isSelected() && !addUserView.stu.isSelected()){
                s += "类型：老师";
            } else if (!addUserView.tea.isSelected() && addUserView.stu.isSelected()) {
                s += "类型：学生";
            }else addUserView.hintMess.setText("请正确选择用户类型");
            s += "密码：" + addUserView.inputPassword.getText().trim();
            try{
                out.writeUTF(s);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        } else if (e.getSource() == addUserView.back) {
            addUserView.setVisible(false);
            new RegisterUserView();
        }
    }
}
